package com.mapbox.mapboxandroiddemo.utils;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.mapbox.mapboxsdk.log.Logger;

import java.util.Map;

import static java.lang.Boolean.parseBoolean;

/**
 * This service is part of Firebase's Cloud Messaging (FCM) setup to listen for incoming messages.
 * With the right server side notification structure, the Maps SDK cache management methods
 * can be hooked into the inbound notification data.
 *
 * As written, THIS SERVICE ISN'T ACTUALLY USED IN THIS APP. You will need to finish setting
 * up a way to send and receive FCM data notifications (https://firebase.google.com/docs/
 * cloud-messaging/concept-options#notifications_and_data_messages) to devices using your project.
 *
 * Other popular options include:
 *
 * Amazon’s Simple Notification Service (https://aws.amazon.com/sns/)
 * SendBird (https://sendbird.com/features/chat-messaging) (built on top of Firebase)
 * Urban Airship (https://www.airship.com/) (built on top of Firebase)
 *
 * See {@link com.mapbox.mapboxandroiddemo.examples.offline.CacheManagementActivity}
 * and https://docs.mapbox.com/android/maps/overview/offline/#cache-management
 * for more information about the Maps SDK's cache management functionality.
 */
public class CustomFirebaseMessagingService extends FirebaseMessagingService {

  private static final String TAG = "CustomMessagingService";

  /**
   * Called when message is received.
   * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
   */
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    // Data messages and notification messages are the two types of Firebase Cloud messages.
    // Data messages are handled here in onMessageReceived whether the app is in the foreground
    // or background. Data messages are the type traditionally used with FCM. Notification messages
    // are only received here in onMessageReceived when the app is in the foreground.
    // When the app is in the background an automatically generated notification is displayed.
    // When the user taps on the notification they are returned to the app. Messages containing
    // both notification and data payloads are treated as notification messages. The Firebase
    // console always sends notification messages. For more information see:
    // https://firebase.google.com/docs/cloud-messaging/concept-options
    if (remoteMessage.getData().size() > 0 && remoteMessage.getNotification() != null) {

      Map<String, String> data = remoteMessage.getData();

      // Get the values from the backend data message. You will need to  More info about this at
      // https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
      boolean invalidateAmbientCache = parseBoolean(data.get("invalidateAmbientCache"));
      boolean setNewMaxAmbientCache = parseBoolean(data.get("setNewMaxAmbientCache"));
      long newMaxAmbientCacheSize = Long.parseLong(data.get("newMaxAmbientCacheSize"));
      boolean clearAmbientCache = parseBoolean(data.get("clearAmbientCache"));
      boolean resetEntireMapDatabase = parseBoolean(data.get("resetEntireMapDatabase"));

      // Now that you have the data from the backend notification, do what you want
      // with it. Save it into SharedPreferences, adjust the cache from this service,
      // etc.
      /*if (invalidateAmbientCache) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
          public void run() {
            OfflineManager fileSource = OfflineManager.getInstance(getApplicationContext());
            fileSource.invalidateAmbientCache(new OfflineManager.FileSourceCallback() {
              @Override
              public void onSuccess() {
                Logger.d(TAG, getString(R.string.cache_invalidated_toast_confirmation));
              }
              @Override
              public void onError(@NonNull String message) {
                Logger.d(TAG, getString(R.string.cache_invalidated_toast_error));
              }
            });
          }
        });
      }*/
    }
  }

  /**
   * Called if InstanceID token is updated. This may occur if the security of
   * the previous token had been compromised. Note that this is called when the InstanceID token
   * is initially generated so this is where you would retrieve the token.
   *
   * @param token the new token generated by the Firebase library
   */
  @Override
  public void onNewToken(String token) {
    Logger.d(TAG, "onNewToken() token: " + token);
  }
}